###############################################################################
#                                                                             #
#    This file is part of the testsuite of the "ssbot" Python module.         #
#    It is distributed under the MIT License. See LICENSE.txt for details.    #
#                                                                             #
###############################################################################


import os
import os.path
import shutil
import sys
import threading
import unittest
import xmlrpclib

sys.path.append('../')

import ssbot.slave
import ssbot.steps

class BuildSlaveTests(unittest.TestCase):
    class TestSlave(ssbot.slave.BuildSlave):
        def __call__(self):
            self.start()

    def setUp(self):
        self.slave_port = 9011
        self.slave = BuildSlaveTests.TestSlave(self.slave_port)
        self.slave_thread = threading.Thread(target=self.slave)
        self.slave_thread.start()
        self.proxy = xmlrpclib.ServerProxy(
            'http://localhost:%d' % self.slave_port, allow_none=True)

    def tearDown(self):
        self.slave.stop()
        self.slave_thread.join()

    def test_mkdir(self):
        test_dir = os.path.join(os.getcwd(), '.slave_test')
        try:
            self.proxy.mkdir(test_dir)
        except Exception as e:
            print(str(e))
        self.assertTrue(os.path.exists(test_dir))
        if os.path.exists(test_dir):
            shutil.rmtree(test_dir)

    def test_run_step(self):
        step_dir = os.path.join(os.getcwd(), '.step_dir')
        new_dir = os.path.join(step_dir, 'new_dir')
        step = ssbot.steps.Step('test', ['mkdir', 'new_dir'], step_dir)
        try:
            self.proxy.mkdir(step_dir)
            self.proxy.run_step(step, step_dir)
        except Exception as e:
            print(str(e))
        self.assertTrue(os.path.exists(new_dir))
        if os.path.exists(step_dir):
            shutil.rmtree(step_dir)


if __name__ == '__main__':
    unittest.main()
